package matrix;

import java.util.ArrayList;
import java.util.List;

public class Solution_54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int xLeft = 0, yLeft = 0, yRight = matrix.length - 1, xRight = matrix[0].length - 1;
        while (xLeft <= xRight && yLeft <= yRight) {
            for (int i = xLeft; i <= xRight; i++) {
                res.add(matrix[yLeft][i]);
            }
            yLeft++;
            for (int i = yLeft; i <= yRight; i++) {
                res.add(matrix[i][xRight]);
            }
            xRight--;
            // 下边：还剩至少一行才走
            if (yLeft <= yRight) {
                for (int i = xRight; i >= xLeft; i--) res.add(matrix[yRight][i]);
                yRight--;
            }
            // 左边：还剩至少一列才走
            if (xLeft <= xRight) {
                for (int i = yRight; i >= yLeft; i--) res.add(matrix[i][xLeft]);
                xLeft++;
            }
        }
        return res;
    }
}
